<template>
  <div class="app-container">
    <el-form ref="form" :rules="rules" :model="form" label-width="120px" size="mini">
      <h4 style="border-left: mediumseagreen solid; padding-left: 10px">基本信息</h4>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" maxlength="100" show-word-limit/>
      </el-form-item>
      <el-form-item label="商品描述">
        <el-input v-model="form.description" type="textarea" rows="3"/>
      </el-form-item>
      <el-form-item label="商品图片" class="picture-item">
        <el-upload
          ref="upload"
          :auto-upload="false"
          action="https://jsonplaceholder.typicode.com/posts/"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus" style="font-size: 14px">添加图片</i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <input id="input" type="text" value="建议尺寸: 750×750像素，开团默认显示第一张图片，最多可添加9张" readonly/>
      </el-form-item>
      <el-form-item label="商品分类" prop="category">
        <el-select v-model="form.categoryId" clearable placeholder="请选择分类">
          <el-option v-for="(item, i) in categoryList" :key="i" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签">
        <el-select
          v-model="form.tags"
          clearable
          multiple
          :multiple-limit="2"
          style="width: 250px"
          placeholder="请选择标签，最多2选择两个"
        >
          <el-option
            v-for="(item, i) in tagsList"
            :key="i"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <h4 style="border-left: mediumseagreen solid; padding-left: 10px">价格与库存</h4>
      <el-form-item label="商品规格">
        <div
          v-for="(item,index) in form.attributes"
          :key="index"
          style="background: #CBCDD048; padding: 10px; margin-top: 10px; border-radius: 5px"
        >
          <el-select
            v-model="item.name"
            clearable
            filterable
            allow-create
            default-first-option
            size="mini"
            placeholder="请选择商品规格"
            @change="handleAttributeChange($event, index)"
            @blur="selectInput($event, index)"
          >
            <el-option
              v-for="(attribute,i) in attributes"
              :key="i"
              :label="attribute.name"
              :value="attribute.name"
            >
            </el-option>
          </el-select>
          <el-button
            icon="el-icon-delete"
            type="danger"
            size="mini"
            circle
            style="float: right;"
            @click="handleAttributeDelete(index)"
          />
          <br/>
          <el-input
            v-for="(generation,i) in item.generations"
            :key="i"
            v-model="item.generations[i]"
            clearable
            style="margin: 5px 10px 0 0; width: 230px"
            :value="generation"
            @blur="updateGenerations"
          >
            <el-button
              v-if="showClose(index)"
              slot="append"
              icon="el-icon-circle-close"
              circle
              @click="handleGenerationDelete(index, i)"
            />
          </el-input>
          <a href="javascript:void(0)" @click="handleGenerationAdd(index)">添加子规格</a>
        </div>
        <el-button
          icon="el-icon-plus"
          size="small"
          style="margin-top: 10px; border: dashed 1px"
          @click="handleAttributeAdd"
        >继续添加规格
        </el-button>
        <div
          v-if="form.attributes[0].name !== ''"
          style="background: #CBCDD048; padding: 10px; margin-top: 10px; border-radius: 5px"
        >
          <el-table
            :data="form.sku"
            height="255"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              width="100"
            >
            </el-table-column>
            <el-table-column
              prop="value"
              label="规格"
              width="100"
            >
            </el-table-column>
            <el-table-column
              label="商品编码"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.productCode"/>
              </template>
            </el-table-column>
            <el-table-column
              label="团购价(元)"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"/>
              </template>
            </el-table-column>
            <el-table-column
              label="成本价(元)"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.cost"/>
              </template>
            </el-table-column>
            <el-table-column
              label="库存"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock"/>
              </template>
            </el-table-column>
          </el-table>
          <el-input v-model="form.oldPrice" size="mini" style="margin-top: 10px">
            <el-button slot="prepend">商品划线价(元)</el-button>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item v-if="form.attributes[0].name === ''" label="商品团购价格" prop="sku">
        <el-input v-model="form.sku[0].price" placeholder="0.00"/>
      </el-form-item>
      <el-form-item v-if="form.attributes[0].name === ''" label="商品库存" prop="sku">
        <el-input v-model="form.sku[0].stock" placeholder="不填默认不限"/>
      </el-form-item>
      <el-form-item v-if="form.attributes[0].name === ''" label="成本价格" prop="sku">
        <el-input v-model="form.sku[0].cost" placeholder="0.00"/>
      </el-form-item>
      <el-form-item v-if="form.attributes[0].name === ''" label="商品编码">
        <el-input v-model="form.sku[0].productCode"/>
      </el-form-item>
      <el-form-item v-if="form.attributes[0].name === ''" label="划线价格" prop="oldPrice">
        <el-input v-model="form.oldPrice"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">创建</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '',
        description: '',
        categoryId: '',
        tags: '',
        attributes: [{ name: '', generations: [] }],
        sku: [{ price: '', cost: '', stock: '', productCode: '' }],
        oldPrice: ''
      },
      generations: [],
      categoryList: ['未分类', '时装'],
      attributes: [
        { name: '尺寸', generations: ['S', 'M', 'L'] },
        { name: '口味', generations: ['不辣', '微辣', '中辣', '重辣'] },
        { name: '重量', generations: ['500g', '1kg', '2kg'] }
      ],
      tagsList: ['团长推荐', '爆款返厂', '网红爆款', '今日必买', '新品上市'],
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择商品类别', trigger: 'blur' }],
        sku: [
          {
            validator: (rule, value, callback) => {
              const reg = /^[1-9](\d*|\d*.\d?[1-9])$/
              for (const item of value) {
                if (item.price === '') {
                  callback(new Error('请输入商品团购价格'))
                } else if (!reg.test(item.price)) {
                  callback(new Error('请输入正确的商品价格'))
                }
                if (item.stock !== '' && !/^[1-9]\d*$/.test(item.stock)) {
                  callback(new Error('请输入正确的库存数'))
                  return
                }
                if (item.cost !== '' && !reg.test(item.cost)) {
                  callback(new Error('请输入正确的划线价格'))
                }
              }
            }, trigger: 'blur'
          }
        ],
        oldPrice: [{ pattern: /^[1-9](\d*|\d*.\d?[1-9])$/, message: '请输入正确的价格格式', trigger: 'blur' }],
        stock: [{ pattern: /^[1-9]\d*$/, message: '请输入正确的库存数', trigger: 'blur' }]
      }
    }
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit()
          this.$message('submit!')
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAttributeDelete(i) {
      if (this.form.attributes.length === 1) {
        this.form.attributes = [{ name: '', generations: [] }]
      } else {
        this.form.attributes.splice(i, 1)
      }
      this.updateGenerations()
    },
    handleAttributeChange(name, i) {
      for (const item of this.attributes) {
        if (item.name === name) {
          this.form.attributes[i].generations = item.generations
          this.updateGenerations()
        }
      }
    },
    handleAttributeAdd() {
      this.form.attributes.push({ name: '', generations: [] })
    },
    handleGenerationDelete(index, i) {
      this.form.attributes[index].generations.splice(i, 1)
      this.updateGenerations()
    },
    handleGenerationAdd(index) {
      this.form.attributes[index].generations.push('')
      if (this.form.attributes[index].generations.length === 1) {
        this.form.attributes[index].generations.push('')
      }
      this.updateGenerations()
    },
    selectInput(e, i) {
      if (e.target.value) {
        this.form.attributes[i].name = e.target.value
        this.handleGenerationAdd(i)
      }
    },
    showClose(i) {
      return this.form.attributes[i].generations.length > 2
    },
    updateGenerations() {
      const arrays = []
      for (const attribute of this.form.attributes) {
        arrays.push(attribute.generations)
      }
      this.form.sku = this.cartesianProduct(arrays)
      console.log(this.form.sku)
    },
    cartesianProduct(arrays) {
      if (!Array.isArray(arrays) || arrays.length === 0) {
        return []
      }
      const result = []
      const n = arrays.length
      const indices = new Array(n).fill(0)
      let hasNext = true
      while (hasNext) {
        let tuple = ''
        for (let i = 0; i < n; i++) {
          const array = arrays[i]
          tuple = tuple + array[indices[i]] + ','
        }
        result.push({ value: tuple })

        let j = n - 1
        while (j >= 0 && indices[j] === arrays[j].length - 1) {
          indices[j] = 0
          j--
        }

        if (j < 0) {
          hasNext = false
        } else {
          indices[j]++
        }
      }
      return result
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

#input {
  border: none;
  color: #BFC3D5FF;
  width: 400px;
  font-size: 13px;
  outline: none;
}

a:link {
  color: blue;
  text-decoration: none;
}

a:hover {
  color: mediumseagreen;
  text-decoration: none;
}
</style>

